<?php
class Sales_Return extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'sales_return',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function create($sales_order_id, $return)
	{
		$judge_result = Sales_Return::judgeCreate($sales_order_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$generate_result = Number_Rules::generate('sales_return', 'XT');
			if ($generate_result['ack'] == SUCCESS)
			{
				$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
				$sales_return = new Sales_Return();
				$sales_return->number = $generate_result['number'];
				$sales_return->warehouse_id = $sales_order['warehouse_id'];
				$sales_return->shop_id = $sales_order['shop_id'];
				$sales_return->sales_order_id = $sales_order_id;
				$sales_return->reason = $return['reason'];
				$sales_return->make_time = CURRENT_DATETIME;
				$sales_return->make_user_id = CURRENT_USER_ID;
				$sales_return->status = Q::ini('custom_flag/sales_return_status/new/value');
				$sales_return->save();
				$sales_return_id = mysql_insert_id();
				Sales_Return_Item::update($return['item'], $sales_return_id);
				QDB::getConn()->execute('update sales_order set handle_status=' . Q::ini('custom_flag/sales_order_handle_status/return/value') . ' where id=' . $sales_order_id);
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'cannot create number');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeCreate($sales_order_id)
	{
		$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
		if ($sales_order)
		{
			if ($sales_order['handle_status'] == Q::ini('custom_flag/sales_order_handle_status/shipped/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'sales order handle status is incorrect');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'sales order is not exists');
		}
	}
	
	static function edit($sales_return)
	{
		$judge_result = Sales_Return::judgeEdit($sales_return['id']);
		if ($judge_result['ack'] == SUCCESS)
		{
			$return = Sales_Return::find('id=?', $sales_return['id'])->getOne();
			$return->reason = $sales_return['reason'];
			$return->save();
			Sales_Return_Item::update($sales_return['item'], $sales_return['id']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeEdit($sales_return_id)
	{
		$sales_return = Sales_Return::find('id=?', $sales_return_id)->asArray()->getOne();
		if ($sales_return)
		{
			if ($sales_return['status'] == Q::ini('custom_flag/sales_return_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'sales return status is incorrect');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'sales return is not exists');
		}
	}
	
	static function storageAudit($sales_return_ids)
	{
		$message = array();
		foreach ($sales_return_ids as $key => $sales_return_id)
		{
			$judge_result = Sales_Return::judgeStorageAudit($sales_return_id);
			if ($judge_result['ack'] == SUCCESS)
			{
				$sales_return = Sales_Return::find('id=?', $sales_return_id)->getOne();
				$sales_return->audit_time = CURRENT_DATETIME;
				$sales_return->audit_user_id = CURRENT_USER_ID;
				$sales_return->status = Q::ini('custom_flag/sales_return_status/storaged/value');
				$sales_return->save();
				Sales_Return_Item::storageAudit($sales_return_id);
			}
			else
			{
				$message[] = $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	static function judgeStorageAudit($sales_return_id)
	{
		$sales_return = Sales_Return::find('id=?', $sales_return_id)->asArray()->getOne();
		if ($sales_return)
		{
			if ($sales_return['status'] == Q::ini('custom_flag/sales_return_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $sales_return['number'] . ': sales return status is incorrect');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $sales_return['number'] . ': sales return is not exists');
		}
	}
	
	static function delete($sales_return_id)
	{
		$judge_result = Sales_Return::judgeDelete($sales_return_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$return = Sales_Return::find('id=?', $sales_return_id)->asArray()->getOne();
			QDB::getConn()->execute('update sales_order set handle_status=' . Q::ini('custom_flag/sales_order_handle_status/shipped/value') . ' where id=' . $return['sales_order_id']);
			Sales_Return::meta()->deleteWhere('id=?', $sales_return_id);
			Sales_Return_Item::meta()->deleteWhere('sales_return_id=?', $sales_return_id);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeDelete($sales_return_id)
	{
		$sales_return = Sales_Return::find('id=?', $sales_return_id)->asArray()->getOne();
		if ($sales_return)
		{
			if ($sales_return['status'] == Q::ini('custom_flag/sales_return_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'sales return status is incorrect');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'sales return is not exists');
		}
	}
	
	static function search($condition, $cp, $ps)
	{
		$where = Sales_return::buildSearchWhere($condition);
		$columns = array(
			'sales_return.*',
			'sales_order_customer_info.shop_buyer_id as shop_buyer_id',
			'shop.name as shop_name',
			'sales_order.number as order_number',
			'warehouse.name as warehouse_name'
		);
		if ($cp == 0 && $ps == 0)
		{
			$select = Sales_Return::find($where)
				->joinLeft('shop', '', 'shop.id=sales_return.shop_id')
				->joinLeft('sales_order', '', 'sales_order.id=sales_return.sales_order_id')
				->joinLeft('sales_order_customer_info', '', 'sales_order_customer_info.sales_order_id=sales_order.id')
				->joinLeft('warehouse', '', 'warehouse.id=sales_return.warehouse_id')
				->order('sales_return.make_time desc')->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Sales_Return::find($where)
				->joinLeft('shop', '', 'shop.id=sales_return.shop_id')
				->joinLeft('sales_order', '', 'sales_order.id=sales_return.sales_order_id')
				->joinLeft('sales_order_customer_info', '', 'sales_order_customer_info.sales_order_id=sales_order.id')
				->joinLeft('warehouse', '', 'warehouse.id=sales_return.warehouse_id')
				->order('sales_return.make_time desc')->setColumns($columns)->limitPage($cp, $ps);
			$pagination= $select->getPagination();
		}
		$return_result = $select->asArray()->getAll();
		return array(
				'ack' => SUCCESS,
				'message' => '',
				'data' => $return_result,
				'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['shop_user_mapping']))
		{
			$where .= ' and sales_return.shop_id in (\'' . implode('\',\'', $condition['shop_user_mapping']) . '\')';
		}
		if ( ! empty($condition['begin_return_time']))
		{
			$where .= ' and sales_return.make_time>=\'' . $condition['begin_return_time'] . '\'';
		}
		if ( ! empty($condition['end_return_time']))
		{
			$where .= ' and sales_return.make_time<=\'' . $condition['end_return_time'] . '\'';
		}
		if ( ! empty($condition['order_number']))
		{
			$where .= ' and sales_order.number=\'' .$condition['order_number'] . '\'';
		}
		if ( ! empty($condition['number']))
		{
			$where .= ' and sales_return.number=\'' . $condition['number'] . '\'';
		}
		if ( ! empty($condition['shop_id']))
		{
			$where .= ' and shop.id=\'' . $condition['shop_id'] . '\'';
		}
		if (isset($condition['warehouse_id']) && (! empty($condition['warehouse_id']) || $condition['warehouse_id'] == array()))
		{
			$warehouse_filter = '0';
			if (is_array($condition['warehouse_id']))
			{
				foreach ($condition['warehouse_id'] as $w)
				{
					$warehouse_filter .= ' or sales_return.warehouse_id=\'' . $w . '\'';
				}
			}
			else
			{
				$warehouse_filter .= ' or sales_return.warehouse_id=\'' . $condition['warehouse_id'] . '\'';
			}
			$where .= " and ($warehouse_filter)";
		}
		if ( ! empty($condition['shop_buyer_id']))
		{
			$where .= ' and sales_order_customer_info.shop_buyer_id=\'' . $condition['shop_buyer_id'] . '\'';
		}
		if ( ! empty($condition['return_status']))
		{
			$return_status_filter = '0';
			foreach (Q::ini('custom_flag/sales_return_status') as $s)
			{
				if (isset($condition['return_status'][$s['value']]) && $condition['return_status'][$s['value']] == $s['value'])
				{
					$return_status_filter .= " or sales_return.status={$s['value']}";
				}
			}
			$where .= " and ($return_status_filter)";
		}
		if ( ! empty($condition['product_number']))
		{
			$sales_return = QDB::getConn()->execute('select distinct(sales_return.id) from sales_return left join sales_return_item on sales_return_item.sales_return_id=sales_return.id left join product_basic on product_basic.id=sales_return_item.product_basic_id where product_basic.number=\''.$condition['product_number'].'\'')->fetchAll();
			$product_number_filter = '';
			foreach ($sales_return as $sr)
			{
				$product_number_filter .= $sr['id'] . ',';
			}
			if ($product_number_filter)
			{
				$where .= " and sales_return.id in (" . substr($product_number_filter, 0, -1) . ")";
			}
			else
			{
				$where .= " and sales_return.id=''";
			}
		}
		return $where;
	}
}